package test4_15.demo02;

public class ProducerAndConsumer {
    public static void main(String[] args) {

        PC pc = new PC(10);

        new Thread(()->{
            while (true){
                pc.pro();
            }
        },"厂家").start();

        new Thread(()->{
            while (true){
                pc.con();
            }
        },"消费者").start();


    }
}


class PC {

    int proNum;
    int tmpNum;

    public PC(int proNum) {
        this.proNum = proNum;
    }

    public synchronized void pro() {
        try {
            while (tmpNum < proNum) {
                System.out.println(Thread.currentThread().getName() + "生产了" + ++tmpNum + "个产品");
                Thread.sleep(100);
            }
            System.out.println("产品制作完毕");
            notify();
            wait();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public synchronized void con() {

        try {
            if (tmpNum > 0) {
                System.out.println(Thread.currentThread().getName() + "购买了一个产品，还剩" + --tmpNum + "个");
                Thread.sleep(100);
            }else {
                System.out.println("产品卖完了");
                notify();
                wait();
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }


    }


}
